<?php

namespace Home\Controller;

use Common\Controller\MemberBaseController;
use Common\Model\ErrorLogModel;
use Common\Model\OrderModel;
use Common\Model\OrderPiaofutongModel;
use Common\Model\OrderReturnModel;
use Common\Model\OrderReturnPiaofutongModel;
use Common\Model\OrderSubModel;
use Think\Controller;

class PiaofutongController extends MemberBaseController
//class PiaofutongController extends Controller
{
    private $piaofutong;

    function __construct()
    {
        parent::__construct();
        vendor('Piaofutong.Piaofutong');
        $this->piaofutong = new \Piaofutong();
    }

    function index()
    {
        $req = $this->piaofutong->scenicSpotList();
        if (!$req['success'])
            $this->error(\Piaofutong::SOAP_ERROE);
        $list = $req['info'];
        $this->assign('list', $list);
        $this->display();
    }

    // 获取实时价格
    function get_real_ticket_price($scenic_spot_info)
    {
        $info = $scenic_spot_info;
        $now = time() - 60 * 60 * 24;
        $tomorrow = date('Y-m-d', $now);
        $today = date('Y-m-d', time());
        $ticket_list = $this->piaofutong->get_ticket_list($info['uuid'], '', true);
        $ticket_price = [];
        foreach ($ticket_list['info'] as $ticket) {
            $aid = $ticket['aid'];
            $pid = $ticket['pid'];
            $prices = $this->piaofutong->get_real_time_storage($aid, $pid, $tomorrow, $today);
            $reail_price = intval($prices['info']['retail_price']);
            if ($reail_price <= 0) {
                $time = date('Y-m-d', strtotime($ticket['order_start']));
                $prices = $this->piaofutong->get_real_time_storage($aid, $pid, $time, $time);
                $_reail_price = intval($prices['info']['retail_price']);
                if ($_reail_price > 0) {
                    $reail_price = floatval($_reail_price) / 100;
                } else {
                    $reail_price = '无票价';
                }
            } else {
                $reail_price = floatval($prices['info']['retail_price']) / 100;
            }
            $ticket['retail_price'] = $reail_price;
            $ticket['remain'] = $prices['info']['remain'] == 9999999 ? '无限' : $prices['info']['remain'];

            $ticket_price[] = $ticket;
        }
        return $ticket_price;
    }

    function scenicSpotInfo()
    {
        $uuid = I('get.uuid');
        $verity_uuid = $this->piaofutong->verity_parm($uuid, '缺少 景区ID');
        if (!$verity_uuid) $this->error($this->piaofutong->get_error());
        $req = $this->piaofutong->scenicSpotInfo($uuid);
        if (!$req['success'])
            $this->error(\Piaofutong::SOAP_ERROE);

        $info = $req['info'];
        $this->assign('info', $info);

        $ticket_price = $this->get_real_ticket_price($info);
        $this->assign('ticket_list', $ticket_price);
        $this->display();
    }

    /*
     * 身份证验证
     * $personId 身份证号
     */
    function ajax_verity_person_ID()
    {
        if (!IS_AJAX)
            $this->error('传输格式错误！');
        $personId = I('get.personId');
        $this->ajaxReturn($this->verity_person_ID($personId));
    }

    function pay()
    {
        $uuid = I('get.uuid');
        $aid = I('get.aid');
        $pid = I('get.pid');
        $verity_uuid = $this->piaofutong->verity_parm($uuid, '缺少 景区ID');
        if (!$verity_uuid) $this->error($this->piaofutong->get_error());
        $req = $this->piaofutong->scenicSpotInfo($uuid);
        if (!$req['success'])
            $this->error(\Piaofutong::SOAP_ERROE);

        $info = $req['info'];
        $this->assign('info', $info);

        $ticket_price = $this->get_real_ticket_price($info);

        $run_time = [];
        $min_price = [];

        $price_list = [];

        foreach ($ticket_price as $key => $item) {
            if ($item['aid'] == $aid and $item['pid'] == $pid and $item['lid'] == $uuid) {
                $run_time['order_start'] = date('Y-m-d', strtotime($item['order_start']));
                $run_time['order_end'] = date('Y-m-d', strtotime($item['order_end']));
                $run_time['refund_rule'] = $item['refund_rule'];
            }
            $min_price[] = $item['retail_price'];
        }

        $min_price = min($min_price);

        $price_num = 3;
        for ($i = 0; $i < $price_num; $i++) {
            $today = date('Y-m-d', time() + 60 * 60 * 24 * $i);
            $tomrrow = date('Y-m-d', time() + 60 * 60 * 24 * ($i + 1));
            $price_list[$i]['today'] = $today;
            $price_list[$i]['tomrrow'] = $tomrrow;
            $price_list[$i]['retail_price'] = $min_price;
        }
//        $ticket_list = $this->piaofutong->get_ticket_list($uuid, '', true);
//        $this->assign('ticket_list', $ticket_list['info']);

        $this->assign('aid', $aid);
        $this->assign('pid', $pid);
        $this->assign('current_price_list', $price_list);
        $this->assign('min_price', $min_price);
        $this->assign('run_time', $run_time);
        $this->assign('ticket_list', $ticket_price);
        $this->display();
    }

    function do_pay()
    {
        $model_order_sub = new OrderSubModel();
        $model_order = new OrderModel();
        $data = I('post.');
        $aid = $data['a_id'];

        // 验证
        $real_name = $data['real_name'];
        if (!$real_name)
            $this->error('必须有 真实姓名');

        $mobile = $data['mobile'];
        if (!$mobile)
            $this->error('必须有 手机号');

        $certificate_no = $data['certificate_no'];
        if (!$certificate_no)
            $this->error('必须有 身份证号');

        $playtime = $data['playtime'];
        if (!$playtime)
            $this->error('必须有 游玩时间');

        $total_price = 0.0;
        $order_sub = $data['orders'];

        $num = 0;
        $_real_price = [];
        $_goods_name = [];
        $info_spot = $this->piaofutong->scenicSpotInfo($data['s_id']);
        $real_tickes_price = $this->get_real_ticket_price($info_spot['info']);
        foreach ($real_tickes_price as $ticket) {
            $retail_price = $ticket['retail_price'];
            $pid = $ticket['pid'];
            $_real_price[$pid] = $retail_price;
            $_goods_name[$pid] = $ticket['title'];
        }

        foreach ($order_sub as $key => $order) {
            $pid = explode('|', $key)[0];
            $price = floatval($_real_price[$pid]) * floatval($order);
            $total_price += floatval($price);
            $num += intval($order);
        }
        if ($num <= 0)
            $this->error('您必须至少选择一种票！');

        // 验证身份证
        $req_verity_person_ID = $this->verity_person_ID($data['certificate_no']);
        if (!$req_verity_person_ID['success'])
            $this->error($req_verity_person_ID['info']);

        $user_id = session('user_id');
        $order_code = $this->piaofutong->getOrderCode();

        $rand_str = random_string(5);
        $sign = md5($order_code . $rand_str);

        $req_union_order_num = $this->get_unionOrderNum($sign, $total_price, $data['s_name'], $data['s_id'], $order_code);
        $unionOrderNum = $req_union_order_num['info'];
        $status_unionOrderNum = $req_union_order_num['status'];
        if (!$status_unionOrderNum)
            $this->error('用户：' . session('user_id') . '统一订单号获取失败！', true);

        $add_data_order = array(
            'order_code' => $order_code,
            'union_order_num' => $unionOrderNum,
            'addtime' => time(),
            's_id' => intval($data['s_id']),
            's_name' => $data['s_name'],
            'playtime' => strtotime($playtime),
            'real_name' => $data['real_name'],
            'user_id' => $user_id,
            'certificate_no' => $data['certificate_no'],
            'mobile' => $data['mobile'],
            'total_price' => $total_price,
            'goods_api' => 'piaofutong',
            'status' => 0,
            'num' => $num,
            'sign' => $sign
        );
        if (!$model_order->create($add_data_order))
            $this->error($model_order->getError());
        $order_id = $model_order->add($add_data_order);
        if (!$order_id)
            $this->error('用户：' . $add_data_order['user_id'] . '主订单添加失败！', true);

        foreach ($order_sub as $key => $order) {
            if (!$order or $order == '0' or $order == 0) break;
            $pid = explode('|', $key)[0]; // 产品id
            $uuid = explode('|', $key)[1]; // 门票id
            $goods_name = $_goods_name[$pid];

            $add_data_order_sub = array(
                'order_id' => $order_id,
                'sub_order_code' => $this->piaofutong->getSubOrderCode($order_code),
                'goods_id' => $pid, // 产品id
                'goods_name' => $goods_name,
                'ticket_id' => $uuid, // 门票id
                'seller_id' => $data['s_id'], // 景区id
                'a_id' => $aid, // 供应商id
                'addtime' => time(),
                'playtime' => strtotime($playtime),
                'goods_sn' => 'piaofutong_' . $pid . '|' . $uuid,
                'user_id' => $user_id,
                'nick_name' => session('user')['name'],
                'phone' => $data['mobile'],
                'real_name' => $data['real_name'],
                'certificate_no' => $data['certificate_no'],
                'mobile' => $data['mobile'],
                'order_code' => $order_code,
                'price' => $_real_price[$pid],
                'num' => $order,
                'total_price' => $total_price,
                'pay_type' => 2,
                'is_api' => 0,
                'is_pay' => 0,
                'is_status' => 0,
                'is_return' => 0,
            );
            if (!$model_order_sub->create($add_data_order_sub))
                $this->error($model_order_sub->getError());
            $is_order = $model_order_sub->add($add_data_order_sub);
            if (!$is_order)
                $this->error('用户：' . $add_data_order_sub['user_id'] . '订单添加失败！', true); // 未完成：错误收集
        }

//        // 添加成功后 跳转到 付款页面
        $this->success('订单添加成功！正在跳转到付款页面...', U('Piaofutong/payment', array('order_id' => $order_id)));
    }

    function payment()
    {
        $order_id = I('get.order_id');
        $model_order = new OrderModel();
        $model_sub_order = new OrderSubModel();
        $info = $model_order->find($order_id);
        $this->pay_type = $info['pay_type'];

        $list_sub_order = $model_sub_order->where(array('order_id' => $order_id))->select();
        $this->assign('info', $info);
        $this->assign('list_sub_order', $list_sub_order);

        $this->display();
    }

    // 退票
    function return_ticket()
    {
        $data = I('get.');
        $order_id = $data['order_id'];
        $model_order = new OrderModel();
        $model_sub_order = new OrderSubModel();

        $info_order = $model_order->find($order_id);
        $where = array(
            'order_code' => $info_order['order_code'],
            'status' => 0
        );
        $_list_sub_order = $model_sub_order->where($where)->select();
        $list_sub_order = [];
        foreach ($_list_sub_order as $sub_order) {
            $_arr = $sub_order;
            $_arr['tprice'] = floatval($sub_order['price']) * floatval($sub_order['num']);
            $list_sub_order[] = $_arr;
        }

        $this->assign('info', $info_order);
        $this->assign('list_sub_order', $list_sub_order);

        $this->display();
    }

    function one_return()
    {
        $data = I('get.');
        $sub_order_code = $data['sub_order_code'];
        $model_order = new OrderModel();
        $model_sub_order = new OrderSubModel();
        $model_order_return = new OrderReturnModel();
        $info_sub_order = $model_sub_order->where(array('sub_order_code' => $sub_order_code))->find();
        if ($info_sub_order['is_status'])
            $this->error('此单已经完结！');

        // 如果 该订单 为未支付 状态
        if (!$info_sub_order['is_pay']) {
            $add_order_return = array(
                'return_order_code' => OrderReturnModel::get_return_order_code(),
                'goods_model' => 'piaofutong',
                'user_id' => session('user_id'),
                'order_id' => $info_sub_order['id'],
                'order_code' => $info_sub_order['sub_order_code'],
                'num' => $info_sub_order['num'],
                'message' => '未付款订单，自动处理通过！',
                'addtime' => time(),
                'overtime' => time(),
                'status' => 1,
                'is_success' => 1,
            );
            if (!$model_order_return->create($add_order_return))
                $this->error($model_order_return->getError());
            $id_order_return = $model_order_return->add($add_order_return);
            $save_sub_order = array(
                'is_status' => 1,
                'is_return' => 1,
                'return_num' => $info_sub_order['num']
            );
            $model_sub_order->where(array('sub_order_code' => $info_sub_order['sub_order_code']))->save($save_sub_order);
            $info_order = $model_order->where(array('order_code' => $info_sub_order['order_code']))->find();
            $save_order = array(
                'is_status' => 2,
                'is_return' => 1,
                'return_num' => intval($info_order['return_num']) + intval($info_sub_order['num']),
                'num' => intval($info_order['num']) - intval($info_sub_order['num']),
                'total_price' => floatval($info_order['total_price']) - (floatval($info_sub_order['num']) * floatval($info_sub_order['price']))
            );
            $model_order->where(array('order_code' => $info_sub_order['order_code']))->save($save_order);
            if (!$id_order_return) $this->error('退单 添加 失败！');
            else
                $this->success('退单 成功！', '/index.php/Home');
        } else {
            $return_order_code = OrderReturnModel::get_return_order_code();
            $add_order_return = array(
                'return_order_code' => $return_order_code,
                'goods_model' => 'piaofutong',
                'user_id' => session('user_id'),
                'order_id' => $info_sub_order['id'],
                'order_code' => $sub_order_code,
                'num' => $info_sub_order['num'],
                'message' => trim(''),
                'addtime' => time()
            );
            if (!$model_order_return->create($add_order_return))
                $this->error($model_order_return->getError());
            $id_order_return = $model_order_return->add($add_order_return);
            if (!$id_order_return) $this->error('退单 添加 失败！');

            $model_order_piaofutong = new OrderPiaofutongModel();
            $piaofutong_order_id = $model_order_piaofutong->where(array('order_id' => $info_sub_order['id']))->getField('ordernum');

            $model_order_return_piaofutong = new OrderReturnPiaofutongModel();
            $add_order_return_piaofutong = array(
                'return_order_code' => $return_order_code,
                'return_order_id' => $id_order_return,
                'order_id' => $info_sub_order['id'],
                'piaofutong_order_id' => $piaofutong_order_id
            );
            if (!$model_order_return_piaofutong->create($add_order_return_piaofutong))
                $this->error($model_order_return_piaofutong->getError());
            if (!$model_order_return_piaofutong->add($add_order_return_piaofutong))
                $this->error('票付通 退单 添加失败！');

            $this->success('退单 申请 成功！请您等待管理员退款！', '/index.php/Home');
            exit();
        }
    }

    function description()
    {

        $this->display();
    }

    private function verity_person_ID($personId)
    {
        $verity_person_id = $this->piaofutong->verity_parm($personId, '缺少 身份证号!');
        if (!$verity_person_id) $this->error($this->piaofutong->get_error());
        return $this->piaofutong->check_personID($personId);
    }

    //    复写 error
    protected function error($message = '', $is_log = false, $jumpUrl = '', $ajax = false)
    {
        if ($is_log) {
            $model_error_log = new ErrorLogModel();
            $data = array(
                'addtime' => time(),
                'controller' => CONTROLLER_NAME,
                'action' => ACTION_NAME,
                'msg' => $message
            );
            if (!$model_error_log->add($data))
                $this->errFile($message);
        }
        parent::error($message, $jumpUrl, $ajax);
    }

    private function get_unionOrderNum($sign, $price, $goods_name, $link_seller, $order_code)
    {
        $req_arr = array();
        // 签名
        $callback_parm = '/order_code/' . $order_code . '/sign/' . $sign;
        $callback = C('PROJECT_URL') . 'index.php/Home/Payment/piaofutong_unionOrderNumCallback' . $callback_parm;
        $amount = $price;
        $des = $goods_name;
        $remark = $goods_name;
        $url = C('MAG_APP_URL') . "core/pay/pay/unifiedOrder?"
            . "trade_no=" . $order_code
            . "&callback=" . $callback
            . "&amount=" . $amount
            . "&title=" . $goods_name
            . "&user_id=" . session('user_id')
            . "&des=" . $des
            . "&remark=" . $remark
            . "&secret=" . C('MAG_SECRET');

        $req = json_decode(file_get_contents($url), true);
        $code = $req['code'];
        $status = $req['success'];
        if (!$status or $code != 100) {
            $req_arr['status'] = 0;
            $req_arr['info'] = "统一订单号获取失败！";
        } else {
            $req_arr['status'] = 1;
            $req_arr['info'] = $req['data']['unionOrderNum'];
        }
        return $req_arr;
    }

    // ajax
    // 调取 当前票 从 今天 到 月末 的 所有价格
    function ajax_get_today_to_endmouth_all_price()
    {
        if (!IS_AJAX)
            $this->error('接口调用错误');
        $aid = I('get.aid');      // 供应商id
        $pid = I('get.pid');      // 产品id

        $start_date = I('get.start_date') == '' ? date('Y-m-d', time()) : date('Y-m-d', strtotime(I('get.start_date')));

        $end_mouth = I('get.end_date');

        $prices = $this->piaofutong->get_real_time_storage($aid, $pid, $start_date, $end_mouth, true);
//        $this->success([$start_date,$end_mouth]);
        $this->success($prices);
    }

    private function errFile($msg)
    {
        $myfile = fopen("piaofutong.txt", "w");
        fwrite($myfile, $msg);
        fclose($myfile);
    }
}